package com.shaw.inappupdate_app.repository

import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException


// send request get version info
fun getVersionInfo(url: String): response {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url(url)
        .get()
        .build()
    return client.newCall(request).execute().use { resp ->
        if (resp.isSuccessful) {
            val body = resp.body
            val json = body.string()
            Log.d("execute", "getVersionInfo: $json")
            val gson = Gson()
            gson.fromJson(json, response::class.java)
        } else throw IOException("get version info fail")
    }
}

data class response(
    val success: Boolean,
    val version: String,
    val url: String
)

// get version info local in build.gradle.kts
@Composable
fun getVersionInfoLocal(): String? {
    val context = LocalContext.current
    val manager = context.packageManager
    val packageName = context.packageName
    return try {
        manager.getPackageInfo(packageName, 0).versionName
    } catch (e: Exception) {
        throw IOException("can`t get versionName")
    }
}

